<template>
	<el-form size="large" class="login-content-form" :rules="dataRules" ref="dataFormRef" :model="state.ruleForm">
		<el-form-item class="login-animation3" prop="phone">
			<el-input text :placeholder="$t('password.phonePlaceholder4')" v-model="state.ruleForm.phone" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon">
						<ele-Position />
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2" prop="code">
			<el-col :span="15">
				<el-input text maxlength="4" :placeholder="$t('mobile.placeholder2')" v-model="state.ruleForm.code" clearable autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon">
							<ele-Position />
						</el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<el-button v-waves @click="handleSendCode" >
					<span class="font-semibold text-xs text-gray-500">
						{{ msg.msgText }}
					</span>
				</el-button>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation2" prop="password">
			<strength-meter
				placeholder="请输入新密码"
				v-model="state.ruleForm.password"
				autocomplete="off"
				:maxLength="20"
				:minLength="6"
				@score="handlePassScore"
			>
				<template #prefix>
					<el-icon class="el-input__icon">
						<ele-Unlock />
					</el-icon>
				</template>
			</strength-meter>
		</el-form-item>

		<el-form-item class="login-animation2" prop="repeatPassword">
			<strength-meter
				placeholder="请重复新密码"
				v-model="state.ruleForm.repeatPassword"
				autocomplete="off"
				:maxLength="20"
				:minLength="6"
				@score="handlePassScore"
			>
				<template #prefix>
					<el-icon class="el-input__icon">
						<ele-Unlock />
					</el-icon>
				</template>
			</strength-meter>
		</el-form-item>

		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit rounded-lg" v-waves @click="handleRegister" :loading="loading">
				<span class="tracking-wide font-semibold">重置密码</span>
			</el-button>
		</el-form-item>

		<div class="relative flex items-center justify-between">
			<div class="text-sm ml-auto">
				<a href="#" style="color: #fff" class="hover:text-blue-600" @click="emit('change', LoginTypeEnum.PASSWORD)"> 返回登录 </a>
			</div>
		</div>
	</el-form>
</template>

<script setup lang="ts" name="register">
import { registerUser, validatePhone, validateUsername } from '/@/api/admin/user';
import { useMessage } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';
import { rule } from '/@/utils/validate';
import { LoginTypeEnum,sendMobileCode } from '/@/api/login';

// 注册生命周期事件
const emit = defineEmits(['afterSuccess', 'change']);

// 按需加载组件
const StrengthMeter = defineAsyncComponent(() => import('/@/components/StrengthMeter/index.vue'));

// 使用i18n
const { t } = useI18n();

// 表单引用
const dataFormRef = ref();

// 加载中状态
const loading = ref(false);

// 密码强度得分
const score = ref('0');

// 组件内部状态
const state = reactive({
	// 是否显示密码
	isShowPassword: false,
	// 表单内容
	ruleForm: {
		phone: '', // 手机号
		code: '', // 验证码
		password: '', // 密码
		repeatPassword: '', // 重复密码
	},
});
const validatorPassword2 = (rule: any, value: any, callback: any) => {
	console.log(value)
	if (value !== state.ruleForm.password) {
		callback(new Error(t('personal.passwordRule')));
	} else {
		callback();
	}
};
// 表单验证规则
const dataRules = reactive({
	phone: [
		{ required: true, message: '手机号不能为空', trigger: 'blur' },
		// 手机号格式验证方法
		{
			validator: rule.validatePhone,
			trigger: 'blur',
		},
	],
	code:[
		{ required: true, message: '验证码不能为空', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{
			min: 6,
			max: 20,
			message: '用户密码长度必须介于 6 和 20 之间',
			trigger: 'blur',
		},
		// 判断密码强度是否达到要求
		{
			validator: (_rule, _value, callback) => {
				if (Number(score.value) < 2) {
					callback('密码强度太低');
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
	repeatPassword: [
		{ required: true, message: '重复密码不能为空', trigger: 'blur' },
		{
			min: 6,
			max: 20,
			message: '用户密码长度必须介于 6 和 20 之间',
			trigger: 'blur',
		},
		{ validator: validatorPassword2, trigger: 'blur' },
		// 判断密码强度是否达到要求
	],
});

// 处理密码强度得分变化事件
const handlePassScore = (e) => {
	score.value = e;
};

/**
 * @name handleRegister
 * @description 注册事件，包括表单验证、注册、成功后的钩子函数触发
 */
const handleRegister = async () => {
	// 验证表单是否符合规则
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		// 开始加载
		loading.value = true;
		// 调用注册API
		await registerUser(state.ruleForm);
		// 注册成功提示
		useMessage().success(t('common.optSuccessText'));
		// 触发注册成功后的钩子函数
		emit('afterSuccess');
	} catch (err: any) {
		// 提示错误信息
		useMessage().error(err.msg);
	} finally {
		// 结束加载状态
		loading.value = false;
	}
};

// 定义响应式对象
const msg = reactive({
	msgText: t('mobile.codeText'),
	msgTime: 60,
	msgKey: false,
});
/**
 * 处理发送验证码事件。
 */
const handleSendCode = async () => {
	const valid = await dataFormRef.value.validateField('phone').catch(() => {});
	if (!valid) return;

	const response = await sendMobileCode(state.ruleForm.phone);
	if (response.data) {
		useMessage().success('验证码发送成功');
		timeCacl();
	} else {
		useMessage().error(response.msg);
	}
};
/**
 * 计算并更新倒计时。
 */
 const timeCacl = () => {
  msg.msgText = `${msg.msgTime}秒后重发`;
  msg.msgKey = true;
  const time = setInterval(() => {
    msg.msgTime--;
    msg.msgText = `${msg.msgTime}秒后重发`;
    if (msg.msgTime === 0) {
      msg.msgTime = 60;
      msg.msgText = t('mobile.codeText');
      msg.msgKey = false;
      clearInterval(time);
    }
  }, 1000);
};
</script>
